var app = getApp();
var a = require("../../utils/public");
var status = require('../../utils/index.js');
var util = require('../../utils/util.js');
var wcache = require('../../utils/wcache.js');

Page({
    mixins: [require('../../mixin/globalMixin.js')],
    data: {
        cartNum: 0,
        rushCategoryData: {
            tabs: [],
            activeIndex: 0
        },
        gid:0,
        pageNum:1,
        switchIndex:0,
        rushList: [],
        info:[],
        tjList: [],
        ercode:'',
        loadMore: true,
        loadText: "加载中...",
        scrollViewHeight: 0,
        pageEmpty: false,
        inputValue: '',
        keyword:'',
        showEmpty:false,
        showLoadMore: true,
        navH:'',
        navBgColor:'#e43011',
        shopname:'',
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        console.log(options);
        this.setData({
            navH: app.globalData.navHeight
        })
        
        if (options.scene){
            const scene = decodeURIComponent(options.scene);
            this.setData({
                gid: scene
            })
        }else{
            this.setData({
                gid: options.id
            })
        }
        
        this.load_goods_data();
    },
    load_goods_data: function () {
        var token = wx.getStorageSync('token');
        var that = this;
        var cur_community = wx.getStorageSync('community');
        console.log('load_goods_begin ');
        that.setData({
            showLoadMore: true,
            loadMore: true,
            loadText: '加载中'
        });
        app.util.request({
            'url': 'entry/wxapp/index',
            'data': {
                controller: 'index.load_gps_supplierinfo',
                token: token,
                pageNum: that.data.pageNum,
                head_id: cur_community.communityId,
                per_page: 8,
                gid:that.data.gid,
                keyword:that.data.keyword
            },
            dataType: 'json',
            success: function (res) {
                if (res.data.code == 1) {
                    console.log(res.data);
                    // wx.setNavigationBarTitle({
                    //     title: res.data.info.shopname
                    // })
                    that.setData({
                        shopname: res.data.info.shopname
                    });
                    if (res.data.list){
                        if (res.data.list.length == 8) {
                            that.setData({
                                loadMore: true,
                                showEmpty: false,
                                showLoadMore:false
                            });
                        } else {
                            that.setData({
                                loadMore: false,
                                showEmpty:false,
                                showLoadMore: true,
                                loadText: '没有更多了'
                            });
                        }
                        var rushList = that.data.rushList.concat(res.data.list);
                        for (var i in rushList) {
                            let date = rushList[i].begin_time2
                            rushList[i].begin_time_date = new Date(date.substring(0, 4) + '-' + date.substring(5, 7) + '-' + date.substring(8, 10)).getTime()
                            rushList[i].isWait = rushList[i].begin_time_date > new Date().getTime()
                            rushList[i].showVideo = true;
                        }
                        that.setData({
                            rushList: rushList,
                            info:res.data.info,
                            ercode:res.data.ercode
                        })
                    }else{
                        that.setData({
                            showLoadMore: false,
                            loadMore: false,
                            showEmpty: false,
                        })
                    }
                    if (that.data.pageNum == 1 && that.data.rushList.length == 0) {
                        that.setData({
                            showEmpty: true
                        })
                    }
                }
            },
            complete: function () {
                // wx.hideLoading();
                setTimeout(function () { wx.hideLoading(); }, 1000);
            }
        })
    },
    onReachBottom: function () {
        var that = this;
        if (that.data.loadMore) {
            var pageNum = that.data.pageNum
            pageNum++;
            that.setData({
                pageNum: pageNum
            })
            this.load_goods_data();
        }
    },
    goLink: function (event) {
        let url = event.currentTarget.dataset.link;
        let needauth = event.currentTarget.dataset.needauth || '';
        console.log(needauth)
        if (needauth) { if (!this.authModal()) return; }
        url && wx.navigateTo({ url })
    },
    goshopCart: function (event) {
        wx.switchTab({
            url: '/lionfish_comshop/pages/order/shopCart',
        })
    },
    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        
    },
    playVideo: function (e) {
        var id = e.currentTarget.dataset.id, index = e.currentTarget.dataset.index, that = this;
        var up = "rushList[" + index + "].showVideo";
        that.setData({
            [up]: false
        })
        this.videoContext = wx.createVideoContext(id);
        this.videoContext.play();
    },
    openSkuThree: function (t) {
        console.log(t);
        // if (!this.authModal()) return;
        var that = this,
            e = t.detail;
        var goods_id = e.actId;
        var options = e.skuList;
        that.setData({
            addCar_goodsid: goods_id
        })

        let list = options.list || [];
        let arr = [];
        if (list && list.length > 0) {
            for (let i = 0; i < list.length; i++) {
                let sku = list[i]['option_value'][0];
                let temp = {
                    name: sku && sku['name'],
                    id: sku && sku['option_value_id'],
                    index: i,
                    idx: 0
                };
                arr.push(temp);
            }
            // arr.sort((a,b)=>{ return a.id - b.id });

            var id = '';
            for (let i = 0; i < arr.length; i++) {
                if (i == arr.length - 1) {
                    id = id + arr[i]['id'];
                } else {
                    id = id + arr[i]['id'] + "_";
                }
            }

            console.log(id)

            var cur_sku_arr = options.sku_mu_list[id] || {};

            that.setData({
                sku: arr,
                sku_val: 1,
                cur_sku_arr: cur_sku_arr,
                skuList: e.skuList,
                visible: true,
                showSku: true,
                is_take_vipcard: e.is_take_vipcard || '',
                is_mb_level_buy: e.is_mb_level_buy || ''
            });
        } else {
            let goodsInfo = e.allData;
            that.setData({
                sku: [],
                sku_val: 1,
                skuList: [],
                cur_sku_arr: goodsInfo
            })
            let formIds = {
                detail: {
                    formId: ""
                }
            };
            formIds.detail.formId = "the formId is a mock one";
            that.gocarfrom(formIds);
        }

    },
    videEndPlay: function (e) {
        var index = e.currentTarget.dataset.index;
        var up = "rushList[" + index + "].showVideo";
        this.setData({
            [up]: true
        })
    },
    openSkuTwo: function (t) {
        console.log(t);
        // if (!this.authModalTwo(t)) return;
        var that = this,
            e = t.currentTarget.dataset.detail;
        var goods_id = e.actId;
        var options = e.skuList;
        that.setData({
            addCar_goodsid: goods_id
        })

        let list = options.list || [];
        let arr = [];
        if (list && list.length > 0) {
            for (let i = 0; i < list.length; i++) {
                let sku = list[i]['option_value'][0];
                let temp = {
                    name: sku && sku['name'],
                    id: sku && sku['option_value_id'],
                    index: i,
                    idx: 0
                };
                arr.push(temp);
            }
            // arr.sort((a,b)=>{ return a.id - b.id });

            var id = '';
            for (let i = 0; i < arr.length; i++) {
                if (i == arr.length - 1) {
                    id = id + arr[i]['id'];
                } else {
                    id = id + arr[i]['id'] + "_";
                }
            }

            console.log(id)

            var cur_sku_arr = options.sku_mu_list[id] || {};

            that.setData({
                sku: arr,
                sku_val: 1,
                cur_sku_arr: cur_sku_arr,
                skuList: e.skuList,
                visible: true,
                showSku: true,
                is_take_vipcard: e.is_take_vipcard || '',
                is_mb_level_buy: e.is_mb_level_buy || ''
            });
        } else {
            let goodsInfo = e.allData;
            that.setData({
                sku: [],
                sku_val: 1,
                skuList: [],
                cur_sku_arr: goodsInfo
            })
            let formIds = {
                detail: {
                    formId: ""
                }
            };
            formIds.detail.formId = "the formId is a mock one";
            that.gocarfrom(formIds);
        }

    },
    /**
   * 确认加入购物车
   */
    gocarfrom: function (e) {
        var that = this;
        var is_just_addcar = 1;
        // wx.showLoading();
        this.setData({
            is_take_vipcard: '',
            is_mb_level_buy: ''
        })
        a.collectFormIds(e.detail.formId);
        that.goOrder();
    },
    goOrder: function () {
        var that = this;
        if (that.data.can_car) {
            that.data.can_car = false;
        }
        var token = wx.getStorageSync('token');
        var community = wx.getStorageSync('community');

        var goods_id = that.data.addCar_goodsid;
        var community_id = community.communityId;
        var quantity = that.data.sku_val;

        var cur_sku_arr = that.data.cur_sku_arr;

        var sku_str = '';
        var is_just_addcar = 1;

        if (cur_sku_arr && cur_sku_arr.option_item_ids) {
            sku_str = cur_sku_arr.option_item_ids;
        }

        let data = {
            goods_id,
            community_id,
            quantity,
            sku_str,
            buy_type: 'dan',
            pin_id: 0,
            is_just_addcar
        }
        util.addCart(data).then(res => {
            if (res.showVipModal == 1) {
                let { pop_vipmember_buyimage } = res.data;
                wx.hideLoading();
                that.setData({ pop_vipmember_buyimage, showVipModal: true, visible: false })
            } else {
                if (res.data.code == 3 || res.data.code == 7) {
                    wx.showToast({
                        title: res.data.msg,
                        icon: 'none',
                        duration: 2000
                    })
                } else if (res.data.code == 4) {
                    wx.hideLoading();
                    wx.navigateTo({ url:'/lionfish_comshop/distributionCenter/pages/loginFixed' })
                    // that.setData({ needAuth: true, showAuthModal: true, visible: false })
                } else if (res.data.code == 6) {
                    let max_quantity = res.data.max_quantity || '';
                    (max_quantity > 0) && that.setData({ sku_val: max_quantity })
                    var msg = res.data.msg;
                    wx.showToast({
                        title: msg,
                        icon: 'none',
                        duration: 2000
                    })
                } else {
                    if (res.data.code == 1) {
                        that.closeSku();
                        (0, status.cartNum)(res.data.total);
                        that.setData({ cartNum: res.data.total })
                        wx.showToast({
                            title: "已加入购物车",
                            icon: 'none',
                            // image: "../../images/addShopCart.png"
                        })
                    } else {
                        var pages_all = getCurrentPages();
                        if (pages_all.length > 3) {
                            wx.redirectTo({
                                url: '/lionfish_comshop/pages/buy/index?type=' + that.data.order.buy_type
                            })
                        } else {
                            wx.navigateTo({
                                url: '/lionfish_comshop/pages/buy/index?type=' + that.data.order.buy_type
                            })
                        }
                    }

                }
            }
        }).catch(res => {
            app.util.message(res || '请求失败', '', 'error');
        })
    },
    /**
   * 关闭购物车选项卡
   */
    closeSku: function () {
        this.setData({
            visible: 0,
            stopClick: false,
        });
    },
    /**
     * 授权成功回调
     */
    authSuccess: function () {
        this.$data = {
            ...this.$data, ...{
                options: {},
                rushCategoryId: "",
                pageNum: 1,
                actIds: [],
                loading: true,
                isScrollTop: true,
                isScrollBottom: false,
                scrollInfo: null,
                isSetCategoryScrollBarTop: true,
                touchStartPos: {
                    pageX: 0,
                    pageY: 0
                }
            }
        }
        let that = this;
        this.setData({
            needAuth: false,
            showAuthModal: false,
            rushList: [],
            categoryScrollBarTop: 0,
            resetScrollBarTop: 50,
            loadMore: true,
            loadText: "加载中...",
            isFirstCategory: true,
            isLastCategory: false,
            pageEmpty: false,
            active_sub_index: 0,
        }, () => {
            that.load_goods_data();
        })
    },

    authModal: function (t) {
        console.log(t);
        t.detail && this.setData({ needAuth: true });
        if (this.data.needAuth) {
            wx.navigateTo({ url:'/lionfish_comshop/distributionCenter/pages/loginFixed' })
            // this.setData({
            //     showAuthModal: !this.data.showAuthModal
            // });
        }
    },
    authModalTwo: function (t) {
        console.log(t);
        t.currentTarget.dataset.detail && this.setData({ needAuth: true });
        if (this.data.needAuth) {
            this.setData({
                showAuthModal: !this.data.showAuthModal
            });
        }
    },

    vipModal: function (t) {
        this.setData(t.detail)
    },
    goDetail: function (e) {
        let idx = e.currentTarget.dataset.id;
        wx.navigateTo({
            url: '/lionfish_comshop/pages/goods/goodsDetail?&id=' + idx,
        })
    },

    /**
     * 搜索栏高度
     */
    getScrollViewHeight: function () {
        var that = this;
        wx.createSelectorQuery().select(".search-bar").boundingClientRect(function (res) {
            res.height && that.setData({
                scrollViewHeight: wx.getSystemInfoSync().windowHeight - res.height
            });
        }).exec();
    },

    getPx: function (t) {
        return Math.round(app.globalData.systemInfo.windowWidth / 375 * t);
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {
        this.setData({
            tabbarRefresh: false,
            changeCarCount: false
        })
    },

    show_search: function () {
        wx.navigateTo({
            url: '/lionfish_comshop/pages/type/search',
        })
    },
    changeNumber: function (t) {
        var a = t.detail;
        console.log(t);
        this.data.focusFlag = false, a && this.canBuyFn(a.value, this.data.current);
    },
    canBuyFn: function (a, e) {
        var u = arguments.length > 2 && void 0 !== arguments[2] ? arguments[2] : {},
            i = this.data.skuList[e].canBuyNum - a,
            s = {
                value: a
            };
        i <= 10 && (s.canBuyMsg = "还可以购买 " + i + " 件"), this.data.canBuyMsg && i > 10 && (s.canBuyMsg = ""),
            this.setData(t({}, s, u));
    },
    outOfMax: function (t) {
        var e = t.detail, canBuyNum = this.data.spuItem.spuCanBuyNum;
        if (this.data.number >= canBuyNum) {
            wx.showToast({
                title: "不能购买更多啦",
                icon: "none"
            })
        }
    },
    openSku: function () {
        if (this.data.needAuth) {
            this.triggerEvent("authModal", true);
            return;
        }
        console.log('step1');
        this.setData({
            stopClick: true,
            disabled: false
        })
        if (this.data.spuItem.skuList.length === void 0) {
            this.triggerEvent("openSku", {
                actId: this.data.spuItem.actId,
                skuList: this.data.spuItem.skuList,
                promotionDTO: this.data.spuItem.promotionDTO,
                is_take_vipcard: this.data.spuItem.is_take_vipcard,
                is_mb_level_buy: this.data.spuItem.is_mb_level_buy,
                allData: {
                    spuName: this.data.spuItem.spuName,
                    skuImage: this.data.spuItem.skuImage,
                    actPrice: this.data.spuItem.actPrice,
                    canBuyNum: this.data.spuItem.spuCanBuyNum,
                    stock: this.data.spuItem.spuCanBuyNum,
                    marketPrice: this.data.spuItem.marketPrice
                }
            });
        } else {
            this.addCart({ value: 1, type: "plus" });
        }
    },
    changeCartNum: function (t) {
        let that = this;
        let e = t.detail;

        (0, status.cartNum)(that.setData({ cartNum: e }));
    },
    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {
        var gid = this.data.gid;
        console.log("lionfish_comshop/pages/type/shopinfo?id=" + gid);
        return {
            path: "lionfish_comshop/pages/type/shopinfo?id=" + gid,
            success: function () { },
            fail: function () { }
        };
    },
    switchShow:function(e){
        console.log(e);
        var index = e.currentTarget.dataset.index;
        this.setData({
            switchIndex: index
        })
    },
    callphoneshop:function(e){
        var moblie = e.currentTarget.dataset.moblie;
        wx.makePhoneCall({
            phoneNumber: moblie,
        })
    },
    watchPassWord: function (event) {
        this.setData({
            inputValue: event.detail.value
        })
        console.log(event.detail.value);
    },
    goResult: function (e) {
        let keyword = this.data.inputValue.replace(/\s+/g, '');
        this.data.keyword = keyword;
        this.data.pageNum = 1;
        this.setData({
            keyword: keyword,
            rushList: []
        })
        wx.pageScrollTo({
            scrollTop: 0
        })
        this.load_goods_data();
    },
    openMap:function(e){
        var lon = parseFloat(e.currentTarget.dataset.lon),
            lat = parseFloat(e.currentTarget.dataset.lat),
            address = e.currentTarget.dataset.addr,
            name = e.currentTarget.dataset.shopname;
        console.log(e);
        wx.openLocation({
            latitude:lat,
            longitude:lon,
            name: name,
            address: address,
            scale: 18
        })
    },
    previewImg: function (e) {
        let idx = e.currentTarget.dataset.idx || 0;
        let prevImgArr = this.data.info.qualifications;
        console.log(prevImgArr);
        wx.previewImage({
            current: prevImgArr[idx],
            urls: prevImgArr
        })
    },
    scan: function (e) {
    　　var current = e.target.dataset.src;
    　　wx.previewImage({
        　　　　current: current,//当前显示图片的http链接，我这边是把图片转成了base64
        　　　　urls: [current] //需要预览的图片http链接列表
    　　})
    },
    gohomeUrl:function(){
        wx.switchTab({ url:'/lionfish_comshop/pages/index/index' })
    }
})